package org.example.im.common.util;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.util.Attribute;
import lombok.experimental.UtilityClass;
import org.example.im.bean.session.Session;
import org.example.im.common.attribute.Attr;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author dingrui
 * @since 2022/2/11
 * @description
 */
@UtilityClass
public class SessionUtil {

    // userId-channel
    private static final Map<String, Channel> uidChannelMap = new ConcurrentHashMap<>();
    // groupId-channelGroup
    private static final Map<String, ChannelGroup> gidChannelGroupMap = new ConcurrentHashMap<>();

    // channel绑定会话
    public void bindSession(Channel c, Session s) {
        uidChannelMap.put(s.getUserId(), c);
        c.attr(Attr.SESSION).set(s);
    }

    public void unBindSession(Channel c) {
        if (!SessionUtil.hasLogin(c)) return;
        Session s = SessionUtil.getSession(c);
        if (Objects.isNull(s)) return;
        c.attr(Attr.SESSION).set(null);
        if (Objects.isNull(s.getUserId())) return;
        uidChannelMap.remove(s.getUserId());
    }

    public boolean hasLogin(Channel c) {
        return c.hasAttr(Attr.SESSION);
    }

    public Session getSession(Channel c) {
        Attribute<Session> attr = c.attr(Attr.SESSION);
        return Objects.nonNull(attr) ? attr.get() : null;
    }

    public Channel getChannel(String userId) {
        return Objects.isNull(userId) ? null : uidChannelMap.get(userId);
    }

    // 群组信息
    public void bindChannelGroup(String groupId, ChannelGroup channelGroup) {
        gidChannelGroupMap.put(groupId, channelGroup);
    }

    public ChannelGroup getChannelGroupByGroupId(String groupId) {
        return gidChannelGroupMap.get(groupId);
    }
}
